package com.ruoyi.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.ProcessModel;
import com.ruoyi.mapper.ProcessModelMapper;
import com.ruoyi.service.ProcessModelService;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 流程模型Service业务层处理
 * 
 * @author chenfei
 * @date 2021-04-29
 */
@Service
public class ProcessModelServiceImpl implements ProcessModelService
{
    private static final Logger logger = LoggerFactory.getLogger(ProcessModelServiceImpl.class);

    @Autowired
    private ProcessModelMapper processModelMapper;
    @Autowired
    private RepositoryService repositoryService;
//    @Autowired
//    private BaseBpmn baseBpmn;
   /**
     * 查询流程模型
     * 
     * @param id 流程模型ID
     * @return 流程模型
     */
    @Override
    public ProcessModel selectActReModelById(String id)
    {
        return processModelMapper.selectActReModelById(id);
    }

    /**
     * 查询流程模型列表
     * 
     * @param actReModel 流程模型
     * @return 流程模型
     */
    @Override
    public List<ProcessModel> selectActReModelList(ProcessModel actReModel)
    {
        return processModelMapper.selectActReModelList(actReModel);
    }

    /**
     * 新增流程模型
     * 
     * @param actReModel 流程模型
     * @return 结果
     */
    @Override
    public int insertActReModel(ProcessModel actReModel)
    {
        actReModel.setCreateTime(DateUtils.getNowDate());
        return processModelMapper.insertActReModel(actReModel);
    }

    /**
     * 修改流程模型
     * 
     * @param actReModel 流程模型
     * @return 结果
     */
    @Override
    public int updateActReModel(ProcessModel actReModel)
    {
        return processModelMapper.updateActReModel(actReModel);
    }

    /**
     * 删除流程模型对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteActReModelByIds(String ids)
    {
        int delflag = 0 ;
        String modelIdArr[] = ids.split(",");
        try{
            if(modelIdArr == null ){
                return 0;
            }
            for(int i=0;i<modelIdArr.length;i++){
                if(StringUtils.isNotNull(modelIdArr[i])){
                    repositoryService.deleteModel(modelIdArr[i]);
                }
            }
            delflag = modelIdArr.length;
        }catch (Exception e){
            logger.error("删除流程模型失败");
            delflag = 0;
        }


        return delflag;
    }

    /**
     * 删除流程模型信息
     * 
     * @param id 流程模型ID
     * @return 结果
     */
    @Override
    public int deleteActReModelById(String id)
    {
        return processModelMapper.deleteActReModelById(id);
    }
    /**
     * 流程模型部署
     *
     * @param modelId 流程模型ID
     * @return 结果
     */
    @Override
    public String deploye(String modelId) {

        try {
            Model modelData = repositoryService.getModel(modelId);
            String deploymentId = modelData.getDeploymentId();
            if(StringUtils.isNotNull(deploymentId)){//说明已经部署完毕
                //return 0;
            }
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes,"UTF-8")).deploy();
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
            //部署完流程更新流程模型表的deployment_id (不知道为啥没更新)
            ProcessModel actReModel = processModelMapper.selectActReModelById(modelId);
            actReModel.setDeploymentId(deployment.getId());
            processModelMapper.updateActReModel(actReModel);
            //更新deployment_id完成
            return deployment.getId();
        } catch (Exception e) {
            logger.error("根据模型部署流程失败：modelId={}", modelId, e);
        }
        return "";
    }
    /***
     * 查询已部署的流程
     *
     * */
    @Override
    public List<ProcessModel> selectDeployeActReModelList(ProcessModel actReModel) {
        return processModelMapper.selectDeployeActReModelList(actReModel);
    }

    /***
     * 刪除已部署的流程
     *
     * */
    @Override
    public int delDeployed(String id) {

//        try {
//            ProcessModel actReModel = processModelMapper.selectActReModelById(id);
//            baseBpmn.deleteDeployed(actReModel.getDeploymentId());
//            //删除流程部署后修改流程模型表的DeploymentId为空
//            actReModel.setDeploymentId("");
//        }catch(Exception e){
//            logger.error("删除流程部署失败，模型id{}，{}",id,e);
//            return 0;
//        }
        return 1;
    }
}
